/************************权限资源管理js*********************************/
define(function(require, exports, module) {

	seajs.use(["jquery1.7","utils","bean/baseService", "bean/backManagerService","confirmbox","ui","zTree","ztree-exedit"], function($,utils,baseService,backManagerService,Confirmbox,ui) {
		
		var ctx = utils.constants.ctx;
		var Map=utils.Map;		
		var gradeConfirmbox;
		var gradeAddOrUp = 1;
		var grade_sort_id = 2; //分类2为年级
		var grade_url = ctx + "/back/base/group-json?sortId=" + grade_sort_id; 
		var updateGradeId = null;
		
		/*ui.mask().show("请稍候...");*/
		
		$(document).on("click",".p_tab1",function(){
			$(this).parent().siblings().removeClass("am-active");
			$(this).parent().addClass("am-active");
		});
		
		$(document).on("click",".p_tab2",function(){
			$(this).parent().siblings().removeClass("am-active");
			$(this).parent().addClass("am-active");
		});
		//zTree基本设置
		var grade_setting = {
				
				data : {
					simpleData :{
						enable :true,
						idKey : "id",
						pIdKey : "parentId" 
					}
					
				},
				async : {
					enable : true,
					url : grade_url, 
					autoParam : ["id","name"]
				},
				
				view : {
					expandSpeed:"",
					addHoverDom : addHoverDom_grade,
					removeHoverDom: removeHoverDom_grade,
					selectedMulti: false		
				},
				edit : {
					enable : true,
					showRemoveBtn:false,
					showRenameBtn:false,
					drag: {
						isCopy: false,
						isMove: false
					}
				},
				callback : { //回调函数  

					onAsyncSuccess: zTreeOnAsyncSuccess_grade,
					onRightClick : zTreeOnRightClick  
		        } 
		};

		//添加按钮图标事件
		function addHoverDom_grade(treeId,treeNode){

			var sObj = $("#" + treeNode.tId + "_span");
			var btn;
			if ($("#editBtn_"+treeNode.id).length>0) return;
			if(treeNode.parentId == null) {
				//添加按钮				
				var addStr = "<span class='button add' id='addBtn_" + treeNode.id
					+ "' title='添加' onfocus='this.blur();'></span>";
				sObj.append(addStr);
				
				btn = $("#addBtn_"+treeNode.id);
				if (btn) btn.bind("click", function(){
					var map = new Map();
					map.put("pId", treeNode.id);
					map.put("submit", "gradeAdd");
					showGradeWBox(map)
				});
			}
			
			//修改按钮
			var editStr = "<span id='editBtn_" +treeNode.id+ "' class='button edit' id='editBtn_" + treeNode.id
			+ "' title='修改' onfocus='this.blur();'></span>";
			sObj.append(editStr);	
			
			btn = $("#editBtn_"+treeNode.id);
			
			if (btn) btn.bind("click", function(){
				var map = new Map();
				map.put("id", treeNode.id);
				map.put("pId", treeNode.parentId);
				map.put("name", treeNode.name);
				map.put("url", treeNode.url);
				map.put("method", treeNode.method);
				map.put("descn", treeNode.descn);
				map.put("orderId", treeNode.orderId);
				map.put("submit", "gradeUpdate");
				showGradeWBox(map);
			});
			
			//删除按钮
			var editStr = "<span id='removeBtn_" +treeNode.id+ "' class='button remove' id='removeBtn_" + treeNode.id
			+ "' title='删除' onfocus='this.blur();'></span>";
			sObj.append(editStr);	
			
			btn = $("#removeBtn_"+treeNode.id);
			
			if (btn) btn.bind("click", function(){

				gradeDelete(treeNode.id, treeNode.parentId);
			});
		}
		//去掉按钮图标事件
		function removeHoverDom_grade(treeId, treeNode) {

			$("#addBtn_"+treeNode.id).unbind().remove();
			$("#editBtn_"+treeNode.id).unbind().remove();
			$("#removeBtn_"+treeNode.id).unbind().remove();
		};
		//加载数据成功后方法
		function zTreeOnAsyncSuccess_grade(){
			
			var zTree = $.fn.zTree.getZTreeObj("grade_tree");
			var nodes = zTree.getSelectedNodes();
			var grade_exNodeList = utils.cookide.getCookieValue("grade_exNodeList").split(',');

			for(var i=0; i < grade_exNodeList.length; i++) {

				zTree.expandNode(zTree.getNodeByParam("id", grade_exNodeList[i], null), true, false, true);
			}
			utils.cookide.setCookie("grade_exNodeList", [], 1, "/");
			ui.mask().hide();
		}

		//添加修改权限资源窗口
		function showGradeWBox(map){
			
			if(map == null) {
				map = new Map();
				map.put("submit", "gradeAdd");
			}

			$.post(ctx + "/base/from_templet", {
				
					"templet_url" : ctx + "/base/from_templet/grade_edit_from"
			}, function(data) {
				
				data = data.replace("{id}", map.get("id"));
				data = data.replace("{parent_id}", map.get("pId"));
				data = data.replace("{name}", map.get("name"));
				data = data.replace("{descn}", map.get("descn"));
				data = data.replace("{orderId}", map.get("orderId"));
				
				if("gradeAdd" == map.get("submit")) {							
					gradeAddOrUp = 1;
				} else if("gradeUpdate" == map.get("submit")) {
					gradeAddOrUp = 0;
				}

				if(gradeConfirmbox == null) {
					gradeConfirmbox = new Confirmbox({
						
						title: "职能部门",
						effect: 'fade',
						message: data,
						width : 700,
						onConfirm: function() {

							if(gradeAddOrUp == 1) {
								gradeAdd();
							} else {
								gradeUpdate();
							}
					    }
					});
				} else {
					
					gradeConfirmbox.before('show',function() {
				       this.set('message', "");
				       this.set('message', data);
				       
				   });
				}

				gradeConfirmbox.show();
			});		
		}

		//添加权限资源方法
		function gradeAdd(){
			
			var pId = $('#grade_parent_id').val();
			var name = $('#grade_name').val();
			var descn = $('#grade_descn').val();
			var orderId = $('#grade_orderId').val();
			
			if(name==""){
				
				alert("名称不能为空");
				return;
			}
				
			var grade = {
				"name" : name,								
				"descn" : descn,
				"sortId" : grade_sort_id,
				"parentId" : pId
			};
			
			try {

				backManagerService.groupAdd(grade);
				alert("添加成功！");
				gradeConfirmbox.hide();
				var zTree = $.fn.zTree.getZTreeObj("grade_tree");
				utils.cookide.setCookie("grade_exNodeList", pId, 1, "/");
				zTree.reAsyncChildNodes(null, "refresh");
				
			} catch (e) {
				alert("添加失败！</br>" + e.message);
			}
		}

		//更新权限资源方法
		function gradeUpdate(){
			
			var id = $('#grade_id').val();
			var pId = $('#grade_parent_id').val();
			var name = $('#grade_name').val();
			var descn = $('#grade_descn').val();
			var orderId = $('#grade_orderId').val();
				
			if(name==""){
				
				alert("名称不能为空");
				return;
			}

			var grade = {
				"id" : id,						
				"name" : name,							
				"descn" : descn,
				"orderId" : orderId,
				"sortId" : grade_sort_id,
				"parentId" : pId
			};
			
			try {

				backManagerService.groupUpdate(grade);
				alert("修改成功！");
				gradeConfirmbox.hide();
				var zTree = $.fn.zTree.getZTreeObj("grade_tree");
				utils.cookide.setCookie("grade_exNodeList", pId, 1, "/");
				zTree.reAsyncChildNodes(null, "refresh");
				
			} catch (e) {
				alert("修改失败！</br>" + e.message);
			}
		}

		//删除权限资源
		function gradeDelete(id, pId) {

			Confirmbox.confirm('是否要删除这个类目', '确认删除框', function() {
				try {

					backManagerService.groupDelete(id);
					alert("删除成功！");
					var zTree = $.fn.zTree.getZTreeObj("grade_tree");
					utils.cookide.setCookie("grade_exNodeList", pId, 1, "/");
					zTree.reAsyncChildNodes(null, "refresh");
					
				} catch (e) {
					alert("删除失败！</br>" + e.message);
				}
			});	
		}

		//显示右键菜单
		function showRMenu(type, x, y) {
			$("#grade_rMenu").show();
			if (type=="root") {
				$("#m_del").hide();
				$("#m_check").hide();
				$("#m_unCheck").hide();
			}
			$("#grade_rMenu").css({"top":y+"px", "left":x+"px", "display":"block"});
		}
		//隐藏右键菜单
		function hideRMenu() {
			$("#grade_rMenu").hide();
		}

		//鼠标右键事件-创建右键菜单
		function zTreeOnRightClick(event, treeId, treeNode) {
			
			var zTree = $.fn.zTree.getZTreeObj("grade_tree");
			if (!treeNode) {
				//zTree.cancelSelectedNode();
				//showRMenu("root", event.clientX - 10, event.clientY - 10);
			} else if (treeNode && !treeNode.noR) { //noR属性为true表示禁止右键菜单
				
				//重置右键添加方法
				var addMap = new Map();
				addMap.put("pId", treeNode.id);
				addMap.put("submit", "gradeAdd");
				$('#grade_rMenu_add').unbind("click");
				$('#grade_rMenu_add').bind("click", function(){
					
					showGradeWBox(addMap);
				});
				if(treeNode.parentId == null) {
					$('#grade_rMenu_add').show();
				} else {
					$('#grade_rMenu_add').hide();
				}
				
				//重置右键修改方法
				var upMap = new Map();
				upMap.put("id", treeNode.id);
				upMap.put("pId", treeNode.parentId);
				upMap.put("name", treeNode.name);
				upMap.put("url", treeNode.url);
				upMap.put("method", treeNode.method);
				upMap.put("descn", treeNode.descn);
				upMap.put("orderId", treeNode.orderId);
				upMap.put("submit", "gradeUpdate");
				$('#grade_rMenu_update').unbind("click");
				$('#grade_rMenu_update').bind("click", function(){
					
					showGradeWBox(upMap);
				});
				//重置右键删除方法
				$('#grade_rMenu_delete').unbind("click");
				$('#grade_rMenu_delete').bind("click", function(){

					gradeDelete(treeNode.id, treeNode.parentId);
				});
				//重置右键权限方法
				$('#grade_rMenu_role').unbind("click");
				$('#grade_rMenu_role').bind("click", function(){
					showGradeRoles(treeNode.id, treeNode.rolesId);
				});

				//重置右键上移方法
				if(treeNode.getPreNode() == null) {
					
					$('#grade_rMenu_up').hide();
				} else {
					$('#grade_rMenu_up').show();
					$('#grade_rMenu_up').unbind("click");
					$('#grade_rMenu_up').bind("click", function(){
						moveGradeTree(treeNode, treeNode.getPreNode());
						hideRMenu();
					});
				}
				//重置右键下移方法
				if(treeNode.getNextNode() == null) {

					$('#grade_rMenu_down').hide();
				} else {
					$('#grade_rMenu_down').show();
					$('#grade_rMenu_down').unbind("click");
					$('#grade_rMenu_down').bind("click", function(){
						moveGradeTree(treeNode, treeNode.getNextNode());
						hideRMenu();
					});
				}

				if (treeNode.newrole && event.target.tagName != "a" && $(event.target).parents("a").length == 0) {
					zTree.cancelSelectedNode();
					showRMenu("root", event.clientX - 40, event.clientY - 150);
				} else {
					zTree.selectNode(treeNode);
					showRMenu("node", event.clientX - 40, event.clientY - 150);
				}
			}
		}

		//排序树
		function moveGradeTree(treeNode1, treeNode2){
			
			var treeNodes = [
					{"id" : treeNode1.id,						
					"orderId" : treeNode2.orderId},
					{"id" : treeNode2.id,						
					"orderId" : treeNode1.orderId}		
			];
			
			try {

				baseService.updateOrder("groupManager", treeNodes);

				var zTree = $.fn.zTree.getZTreeObj("grade_tree");
				utils.cookide.setCookie("grade_exNodeList", treeNode1.parentId, 1, "/");
				zTree.reAsyncChildNodes(null, "refresh");
				
			} catch (e) {
				alert("移动失败！</br>" + e.message);
			}
		}
		
		var zNodes=[]; 
		hideRMenu();
		$.fn.zTree.init($("#grade_tree"), grade_setting, zNodes);

		$("#grade_tree").prev().unbind('click');
		$("#grade_tree").prev().bind('click', function(){
			showGradeWBox(null);
		});
		$("#grade_rMenu").hover( //鼠标离开右键菜单隐藏事件
				function () {		
				},
				function () {
					hideRMenu();
				}
		);
		
		var updateRolesCb;
		function showGradeRoles(gradeId, roleIds){
			
			updateGradeId = gradeId;
			var data = '<div id="grade_role_info" style="min-height: 100px;">';
			
			var roles;
			try{
				roles = backManagerService.loadAllroles();
			} catch (e) {
				alert("加载数据失败:" + e.message);
				return;
			}
			
			for(var i=0;i<roles.length;i++) {
				
				var v = 20;
				if(roles[i].name != null && roles[i].name.length > 6) {
					v = 0;
				}
				var checked = '';
				if(roleIds.indexOf(roles[i].id) > -1) {
					checked = 'checked="checked"';
				}
				data += '<span style="overflow: hidden;margin-bottom:' + v + 'px;width: 100px;display: block;float: left;">' 
						+ '<input type="checkbox" ' + checked + ' name="grade_roles" id="grade_role_'
						+ roles[i].id + '">' + roles[i].name + '</span>';

			}
			data += '</div>'
			
			if(updateRolesCb == null) {
				updateRolesCb = new Confirmbox({
					
					trigger: '#grade_role_confirmbox',
					title: "分配角色",
					message: data,
					width : 450,
					onConfirm: function() {
			
						var ch = $('#grade_role_info input[name="grade_roles"]');
						var newRoleIds = []; //新角色ids
						
						for(var i=0; i<ch.length;i++) {

							if("checked" == ch.eq(i).attr("checked")) {
								var id = parseInt(ch.eq(i).attr("id").replace("grade_role_", ""));
								newRoleIds.push(id);
							}
						}
						
						try{

							backManagerService.groupAllotRole(updateGradeId, newRoleIds);
							alert("分配角色成功！");
							this.hide();
							window.location.reload();
						} catch (e) {
							alert("分配角色失败:" + e.message);
							return;
						}
					}
				});
			} else {					
				updateRolesCb.before('show',function() {

			       this.set('message', "");
			       this.set('message', data);		       
			   });
			}
			updateRolesCb.show();			
		}
	});

});

